import time

import requests
from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
browser = webdriver.Chrome(chrome_options=options, executable_path="chromedriver.exe")
# 保持最大窗口
browser.maximize_window()
# 跳转到outlook

browser.get("https://mail.intra.nsfocus.com/")
time.sleep(3)
# 输入账号
browser.find_elements_by_id('username')[0].send_keys('ar@intra.nsfocus.com')
# 输入密码
browser.find_elements_by_id('password')[0].send_keys('t56yapso!')
time.sleep(1)
# 点击登录按钮
browser.find_elements_by_class_name('signinTxt')[0].click()
time.sleep(3)
cookies = 'QuantumMetricUserID=263793eb82d381e580cd9e89f80a7453; ' \
          '_ga_PMXYWTHPVN=GS1.1.1664514653.39.1.1664514675.38.0.0; PrivateComputer=true; ' \
          '_ga=GA1.2.1837734744.1662648581; _ga_Y7CNRMFF6J=GS1.1.1668775557.33.1.1668776317.26.0.0; '
x_canary = ''
# list_cookies = list(cookies)
req = browser.get_cookies()
for r in range(0, len(req)):
    c_token = req[r]['name'] + '=' + req[r]['value'] + ';'
    cookies = cookies + c_token
    if req[r]['name'] == 'X-OWA-CANARY':
        x_canary = x_canary.join(req[r]['value'])
        # print(x_canary, '---------canary')
    # print(c_token, '---------', r)
    # print(cookies, '---------', r)
print(cookies, '----------cookies')
print(x_canary, '-----------canary')
time.sleep(3)
# 判断是否有未读邮件
no_read = \
    browser.find_elements_by_xpath('/html/body/div[2]/div/div[3]/div[5]/div/div[1]/div/div[1]/div[2]/div/div[5]/'
                                   'div[2]/div/div/div[2]/div/div/div[1]/div[2]/div[2]/div/div/div[2]/div[1]/div/'
                                   'div[1]/span/div/div[2]/span')[0].text.strip()
# print(no_read,'-----', type(no_read))
# print(no_read.isspace())

# 获取收件箱内邮件xpath
from_xpath_a = "/html/body/div[2]/div/div[3]/div[5]/div/div[1]/div/div[5]/div[3]/div/div[2]/div/div/div/div[5]/div[3]/" \
               "div[1]/div[3]/div[1]/div/div/div[2]"
# 无未读邮件
if len(no_read) == 0:
    print('1--暂无未读信息')
# 有未读邮件
elif int(no_read) != 0:
    print('1--检测到未读邮件，开始运行程序')
    headers = {
        'authority': 'mail.intra.nsfocus.com',
        'method': 'POST',
        'path': '/owa/service.svc?action=GetConversationItems&EP=1&UA=0&ID=-4&AC=1',
        'scheme': 'https',
        'accept': '*/*',
        'accept-encoding': 'gzip, deflate, br',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7,en-US;q=0.6',
        'action': 'GetConversationItems',
        'cache-control': 'no-cache',
        # 'client-request-id': '1CE8FB38271D49B7AD10684C434EE998_166813403194306',
        'client-request-id': '1CE8FB38271D49B7AD10684C434EE998_166903623700506',
        'content-length': '0',
        'content-type': 'application/json; charset=UTF-8',
        'origin': 'https://mail.intra.nsfocus.com',
        'pragma': 'no-cache',
        'sec-ch-ua': '"Google Chrome";v="107", "Chromium";v="107", "Not=A?Brand";v="24"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36',
        'x-owa-actionid': '-4',
        'x-owa-actionname': 'GetConversationItemsAction',
        'x-owa-attempt': '1',
        # 'x-owa-clientbegin':'2022-11-29T07:43:02.331',
        # 'x-requested-with':'XMLHttpRequest',
        'x-owa-clientbuildversion': '15.1.2375.37',
        'x-owa-urlpostdata': '%7B%22__type%22%3A%22GetConversationItemsJsonRequest%3A%23Exchange%22%2C%22Header%22%3A%7B%22__type%22%3A%22JsonRequestHeaders%3A%23Exchange%22%2C%22RequestServerVersion%22%3A%22V2017_08_18%22%2C%22TimeZoneContext%22%3A%7B%22__type%22%3A%22TimeZoneContext%3A%23Exchange%22%2C%22TimeZoneDefinition%22%3A%7B%22__type%22%3A%22TimeZoneDefinitionType%3A%23Exchange%22%2C%22Id%22%3A%22China%20Standard%20Time%22%7D%7D%7D%2C%22Body%22%3A%7B%22__type%22%3A%22GetConversationItemsRequest%3A%23Exchange%22%2C%22Conversations%22%3A%5B%7B%22__type%22%3A%22ConversationRequestType%3A%23Exchange%22%2C%22ConversationId%22%3A%7B%22__type%22%3A%22ItemId%3A%23Exchange%22%2C%22Id%22%3A%22AAQkADk5NDYxNWU5LWIwYmQtNDg5MS05OGYzLTlhY2VkYTU4NTdlYQAQAE62XCxjdt2%2FIyRirYtyeJI%3D%22%7D%2C%22SyncState%22%3A%22%22%7D%5D%2C%22ItemShape%22%3A%7B%22__type%22%3A%22ItemResponseShape%3A%23Exchange%22%2C%22BaseShape%22%3A%22IdOnly%22%2C%22FilterHtmlContent%22%3Atrue%2C%22BlockExternalImagesIfSenderUntrusted%22%3Atrue%2C%22BlockContentFromUnknownSenders%22%3Afalse%2C%22AddBlankTargetToLinks%22%3Atrue%2C%22ClientSupportsIrm%22%3Atrue%2C%22InlineImageUrlTemplate%22%3A%22data%3Aimage%2Fgif%3Bbase64%2CR0lGODlhAQABAIAAAAAAAP%2F%2F%2FyH5BAEAAAEALAAAAAABAAEAAAIBTAA7%22%2C%22FilterInlineSafetyTips%22%3Atrue%2C%22MaximumBodySize%22%3A2097152%2C%22MaximumRecipientsToReturn%22%3A20%2C%22CssScopeClassName%22%3A%22rps_5fc2%22%2C%22InlineImageUrlOnLoadTemplate%22%3A%22InlineImageLoader.GetLoader().Load(this)%22%2C%22InlineImageCustomDataTemplate%22%3A%22%7Bid%7D%22%2C%22ExcludeBindForInlineAttachments%22%3Atrue%2C%22CalculateOnlyFirstBody%22%3Atrue%7D%2C%22ShapeName%22%3A%22ItemPart%22%2C%22SortOrder%22%3A%22DateOrderDescending%22%2C%22MaxItemsToReturn%22%3A20%2C%22FoldersToIgnore%22%3A%5B%7B%22__type%22%3A%22FolderId%3A%23Exchange%22%2C%22ChangeKey%22%3A%22AQAAAA%3D%3D%22%2C%22Id%22%3A%22AAMkADk5NDYxNWU5LWIwYmQtNDg5MS05OGYzLTlhY2VkYTU4NTdlYQAuAAAAAABpKvM0EgDMQLUjgeQsgVkCAQBsXJFIywPoS4IuVpho%2F7iPAAAAP%2FjsAAA%3D%22%7D%5D%7D%7D',
        'cookie': cookies,
        'x-owa-canary': x_canary
    }
    params = (
        ('action', 'GetConversationItems'),
        ('EP', '1'),
        ('UA', '0'),
        ('ID', '-4'),
        ('AC', '1')
    )
    response = requests.post('https://mail.intra.nsfocus.com/owa/service.svc?', params=params, headers=headers)
    req_json = response.json()
    # print(req_json)
    res_html = \
        req_json['Body']['ResponseMessages']['Items'][0]['Conversation']['ConversationNodes'][0]['QuotedTextList'][0]
    with open('res_html.html', 'w', encoding='utf-8') as f:
        f.write(res_html)
        print('2--写入html页面成功')
    # 关闭窗口
    browser.quit()
    time.sleep(3)
    print('3--关闭outlook窗口，打开下载的邮件详情页')